package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.AccountActivity;
import com.ca.ridersclubapplication.ClubActivity;
import com.ca.ridersclubapplication.PaperActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.bean.BannerInfo;
import com.ca.ridersclubapplication.data.bean.MainHeaderInfo;
import com.ca.ridersclubapplication.data.bean.MiniClubInfo;
import com.ca.ridersclubapplication.data.bean.PaperInfo;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.linstener.BannerCardOnPageChangeListener;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ActivityStarter;
import com.ca.ridersclubapplication.util.PaperUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.button.IconButton;
import com.ca.ridersclubapplication.view.card.PaperCard;
import com.ca.ridersclubapplication.view.card.PostCommentCard;
import com.ca.ridersclubapplication.view.header.MainHeaderView;
import com.ea.ui.core.basic.EATextField;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HasHeaderPaperAdapter extends RecyclerView.Adapter<HasHeaderPaperAdapter.PaperHolder> {

    private Activity activity;
    private List<BannerInfo> bannerInfoList;
    private List<MiniClubInfo> miniClubInfoList;
    private List<PaperCardDto> list;

    private MainHeaderView mainHeaderView;

    public int mainHeaderHeight;

    public HasHeaderPaperAdapter(List<BannerInfo> bannerInfoList, List<MiniClubInfo> miniClubInfoList, List<PaperCardDto> list) {
        this.bannerInfoList = bannerInfoList == null ? new ArrayList<>() : bannerInfoList;
        this.miniClubInfoList = miniClubInfoList == null ? new ArrayList<>() : miniClubInfoList;
        this.list = list == null ? new ArrayList<>() : list;
        this.list.add(0, null);
    }

    @NonNull
    @Override
    public PaperHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.paper_item_layout, parent, false);
        return new PaperHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull PaperHolder holder, int position) {

        if (position == 0) {

            mainHeaderView = holder.mainHeaderView;
            mainHeaderView.setActivity(activity);

            holder.mainHeaderView.setVisibility(View.VISIBLE);
            holder.paperCard.setVisibility(View.GONE);

            //  设置广告Banner图片URL
            String[] array = new String[bannerInfoList.size()];
            for (int i = 0; i < array.length; i++) {
                array[i] = bannerInfoList.get(i).getImageUrl();
            }
            holder.mainHeaderView.bannerCard.setActivity(activity);
            holder.mainHeaderView.bannerCard.setMiniClubInfoList(bannerInfoList);
            //  设置背景图片高度
            ImageView bgView = holder.mainHeaderView.bannerCard.imageView;
            bgView.post(() -> {
                int width = bgView.getWidth();
                ViewGroup.LayoutParams params = bgView.getLayoutParams();
                params.height = (int) (width * 2.0 / 3);
            });

            //  设置用户关注的车友会卡片列表
            holder.mainHeaderView.clubSquareListView.setList(miniClubInfoList);

            holder.mainHeaderView.bannerCard.addOnPageChangeListener(new BannerCardOnPageChangeListener(
                    activity,
                    holder.mainHeaderView.bannerCard.imageView,
                    array
            ));

            holder.mainHeaderView.post(() -> {
                mainHeaderHeight = holder.mainHeaderView.getMeasuredHeight();
            });
        }
        else {

            holder.mainHeaderView.setVisibility(View.GONE);
            holder.paperCard.setVisibility(View.VISIBLE);

            PaperCardDto dto = list.get(position);
            holder.paperCard.setPaper(dto);

            //  解析内容，获取文章图片列表
            String[] array = PaperUtils.parsePaperImageUrlArray(dto.getContent());
            if (activity != null) {
                holder.paperCard.imageView.setOnClickListener(v -> {
                    ActivityStarter.startImageActivity(
                            activity,
                            array,
                            0);
                });

                holder.paperCard.headerView.setOnClickListener(v -> {
                    Intent intent = new Intent(activity, AccountActivity.class);
                    intent.putExtra("accountId", dto.getAuthorId());
                    activity.startActivity(intent);
                });

                holder.paperCard.clubNameView.setOnClickListener(v -> {
                    Intent intent = new Intent(activity, ClubActivity.class);
                    intent.putExtra("clubId", dto.getClubId());
                    activity.startActivity(intent);
                });

                final IconButton supportButton = holder.paperCard.supportButton;
                final IconButton commentButton = holder.paperCard.commentButton;
                //  请求文章点赞数
                PaperRequester.getSupportCount(activity, dto.getId(), new AfterExecutor<Long>() {
                    @Override
                    public void execute(Result<Long> result) {
                        if (result.isSuccess()) {
                            supportButton.setValue(result.getData());
                        }
                    }
                });

                //  请求文章评论数
                PaperRequester.getCommentCount(activity, dto.getId(), new AfterExecutor<Long>() {
                    @Override
                    public void execute(Result<Long> result) {
                        if (result.isSuccess()) {
                            commentButton.setValue(result.getData());
                        }
                    }
                });

                //  请求文章是否点赞
                if (DataHandler.isLogin(activity)) {
                    PaperRequester.isSupport(activity, dto.getId(), new AfterExecutor<Boolean>() {
                        @Override
                        public void execute(Result<Boolean> result) {
                            Boolean isSupport = result.getData();
                            //  已点赞
                            supportButton.setActive(
                                    result.isSuccess()
                                            && isSupport != null
                                            && isSupport);
                        }
                    });
                }

                //  点赞按钮事件
                supportButton.setOnClickListener(v -> {

                    supportButton.setEnabled(false);

                    if (!supportButton.isActive()) {
                        //  如果没有点赞，则发起点赞请求
                        PaperRequester.addSupport(activity, dto.getId(), new AfterExecutor<String>() {
                            @Override
                            public void execute(Result<String> result) {
                                supportButton.setActive(true);
                                if (result.isSuccess()) {
                                    //  点赞成功，改变按钮样式，数据 + 1
                                    long count = supportButton.getValue() + 1;
                                    supportButton.setValue(count);
                                    dto.setSupportCount(count);
                                }
                                else {
                                    Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                                supportButton.setEnabled(true);
                            }
                        });
                    }
                    else {
                        //  发起取消点赞请求
                        PaperRequester.deleteSupport(activity, dto.getId(), new AfterExecutor<String>() {
                            @Override
                            public void execute(Result<String> result) {
                                supportButton.setActive(false);
                                if (result.isSuccess()) {
                                    //  点赞成功，改变按钮样式，数据 - 1
                                    long count = supportButton.getValue() - 1;
                                    supportButton.setValue(count);
                                    dto.setSupportCount(count);
                                }
                                else {
                                    Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                                supportButton.setEnabled(true);
                            }
                        });
                    }
                });

                //  评论按钮事件
                commentButton.setOnClickListener(v -> {

                    //  弹出快捷评论对话框
                    @SuppressLint("InflateParams")
                    View view = LayoutInflater.from(activity).inflate(R.layout.quick_comment_dialog_layout, null);
                    Dialog dialog = new Dialog(activity);
                    dialog.setContentView(view);
                    dialog.show();

                    PostCommentCard pcc = view.findViewById(R.id.card_post);
                    TextView titleView = pcc.titleView;
                    EATextField input = pcc.input;
                    Button submitButton = pcc.submitButton;
                    titleView.setText(dto.getTitle());
                    submitButton.setOnClickListener(v1 -> {
                        String content = Objects.requireNonNull(input.getText()).toString();
                        if (!content.trim().isEmpty()) {

                            submitButton.setEnabled(false);

                            //  发送请求
                            PaperRequester.addComment(activity, dto.getId(), content, new AfterExecutor<String>() {
                                @Override
                                public void execute(Result<String> result) {
                                    if (result.isSuccess()) {
                                        //  发送成功
                                        dialog.dismiss();
                                        //  数据 + 1
                                        long count = commentButton.getValue() + 1;
                                        commentButton.setValue(count);
                                        dto.setCommentCount(count);
                                    }
                                    else {
                                        Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                                    }

                                    submitButton.setEnabled(true);
                                }
                            });
                        }
                        else {
                            Toast.makeText(activity, "请输入评论的内容", Toast.LENGTH_SHORT).show();
                        }
                    });
                });

                //  文章点击事件
                holder.paperCard.setOnClickListener(v -> {
                    Intent intent = new Intent(activity, PaperActivity.class);
                    intent.putExtra("paperId", dto.getId());
                    activity.startActivity(intent);;
                });

                //  文章删除回调视图
                final int dindex = position;
                DataHandler.putView("PaperDelete:" + dto.getId(), new CallbackView() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void update() {
                        Handleable data = DataHandler.getData("PaperDelete:" + dto.getId());
                        if (data instanceof BooleanEntity) {
                            BooleanEntity isDelete = (BooleanEntity) data;
                            if (isDelete.getValue()) {
                                //  删除该文章
                                list.remove(dindex);
                                notifyDataSetChanged();
                            }
                        }
                    }
                });
            }
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<PaperCardDto> list) {

        if (list == null) {
            list = new ArrayList<>();
        }

        if (!this.list.equals(list)) {
            this.list = list;
            this.list.add(0, null);
            notifyDataSetChanged();
        }
    }

    /**
     * 向尾部追加新的数据
     * @param list 传入的列表为新的数据列表
     */
    public void appendList(List<PaperCardDto> list) {

        if (list == null) {
            return;
        }

        int startPosition = getItemCount();

        //  添加数据
        this.list.addAll(list);

        //  如果没有新的数据添加，弹出提示
        if (startPosition == this.list.size()) {
            Toast.makeText(activity, "暂时没有更多数据了", Toast.LENGTH_SHORT).show();
        }

        notifyItemRangeInserted(startPosition, this.list.size() - startPosition);
    }

    /**
     * 向头部追加新的数据
     * @param list 传入的列表为新的数据列表
     */
    public void appendListToTop(List<PaperCardDto> list) {

        if (list == null) {
            return;
        }

        //  添加数据
        for (PaperCardDto dto : list) {
            this.list.add(1, dto);
        }

        //  如果没有新的数据添加，弹出提示
        if (list.size() == 0) {
            Toast.makeText(activity, "暂时没有更多数据了", Toast.LENGTH_SHORT).show();
        }

        notifyItemRangeInserted(1, list.size());
    }

    public MainHeaderView getMainHeaderView() {
        return mainHeaderView;
    }

    public void setMainHeader(List<BannerInfo> bannerInfoList, List<MiniClubInfo> miniClubInfoList) {
        this.bannerInfoList = bannerInfoList == null ? new ArrayList<>() : bannerInfoList;
        this.miniClubInfoList = miniClubInfoList == null ? new ArrayList<>() : miniClubInfoList;
        notifyItemChanged(0);
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    public static class PaperHolder extends RecyclerView.ViewHolder {

        public MainHeaderView mainHeaderView;
        public PaperCard paperCard;

        public PaperHolder(@NonNull View itemView) {
            super(itemView);
            mainHeaderView = itemView.findViewById(R.id.mainHeader);
            paperCard = itemView.findViewById(R.id.card_paper);
        }
    }
}
